package com.lmwyc.core;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lmwyc.bean.UserSession;
import com.lmwyc.constant.Constant;
import com.lmwyc.mapper.UserSessionMapper;
import com.lmwyc.util.HttpUtil;
import com.lmwyc.util.MailUtil;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class SessionThread implements Runnable {
	private static final Logger logger = LoggerFactory.getLogger(SessionThread.class);

	private UserSession user;
	private UserSessionMapper userSessionMapper;
	private MailUtil mail;
	private String invalidTitle;
	private String invalidContent = "";

	public SessionThread(UserSession user, MailUtil mail, UserSessionMapper userSessionMapper, String invalidTitle,
			String invalidContent) {
		this.user = user;
		this.mail = mail;
		this.userSessionMapper = userSessionMapper;
		this.invalidTitle = invalidTitle;
		this.invalidContent = invalidContent;
	}

	@Override
	public void run() {
		String result = flushSession(user.getUserSessionId());
		logger.info(user.getUserName() + " 刷新session成功");
		if (result == null || "".equals(result) || result.startsWith("﻿<!DOCTYPE html>")) {
			logger.error(user.getUserName() + " 的session会话失效");
			logger.error(result);
			userSessionMapper.updateUser(user.getUserName(), null, 0);
			if (user.getPhone() != null && user.getPhone().trim().length() > 0) {
				Twilio.init(Constant.ACCOUNT_SID, Constant.AUTH_TOKEN);
				PhoneNumber to = new PhoneNumber("+86" + user.getPhone());
				PhoneNumber from = new PhoneNumber(Constant.PHONE_FROM);
				Message message = Message.creator(to, from, invalidContent).create();
				logger.error(user.getUserName() + " 已发送短信 " + message.getSid());
			} else {
				mail.sendSimpleMail(user.getEmail(), invalidTitle, invalidContent);
			}
		}
	}

	public String flushSession(String sessionId) {
		String[] postUrls = { Constant.GET_AREA_LIST };
		String[] getUrls = { Constant.INDEX_PAGE, Constant.RECORD_PAGE };
		Random random = new Random();
		String res = "";
		if (random.nextInt(100) % 2 == 0) {
			res = HttpUtil.sendPost(postUrls[0], null, Constant.encoding, sessionId);
		} else {
			if (random.nextInt(100) % 2 == 0) {
				res = HttpUtil.sendGet(getUrls[0], null, Constant.encoding, sessionId);
			} else {
				res = HttpUtil.sendGet(getUrls[1], null, Constant.encoding, sessionId);
			}
		}
		return res;
	}
}
